﻿using Ldt.AnalysisLabel;
using LdtJudge.DataEngine.CallInterface.CommHelp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace LdtJudge.DataEngine.Common.AnalysisLabel
{
    public class LabelClass
    {
        public string CaseCauseName(string CaseCauseID, string CaseID, string CaseTypeID, string XMLDataSource, string systemAPIUrl)
        {

            List<KeyValuePair<string, bool>> valueList =  GetLabel(CaseTypeID, systemAPIUrl);

            //InteractiveShow.LogShow("案件名称 ajmc  标签"+ JsonConvert.SerializeObject(valueList));
            foreach (KeyValuePair<string, bool> valuekey in valueList)
            {
                try
                {
                    LabelAnalysisRequestDTO labelAnalysisRequestDTO = new LabelAnalysisRequestDTO()
                    {
                        CaseCauseID = CaseCauseID,
                        CaseID = CaseID,
                        CaseTypeID = CaseTypeID,
                        Expression = valuekey.Key,
                        //SourceName = "ElementCenter",
                        XMLDataSource = XMLDataSource
                    };


                    string mssge= JsonConvert.SerializeObject(labelAnalysisRequestDTO);
                    //InteractiveShow.LogShow("案件名称 ajmc  进入匹配");
                    try
                    {
                        string result = AnalysisLabelClass.analysisLabelHelper.ResolveOutPutTempletLabel(labelAnalysisRequestDTO);
                        if (!string.IsNullOrEmpty(result))
                        {
                            return result;
                        }
                    }
                    catch (Exception fxx)
                    {
                        string message = fxx.ToString();
                        //InteractiveShow.LogShow("案件名称 ajmc  进入匹配");
                    }
                   
                }
                catch (Exception ex)
                {
                    //InteractiveShow.LogShow("案件名称 ajmc  错误：" + JsonConvert.SerializeObject(ex)); 
                }
                
            }
            return null;


        }
        /// <summary>
        /// 获取标签
        /// </summary>
        /// <param name="CaseTypeId">案件类型ID</param>
        /// <returns></returns>
        public List<KeyValuePair<string, bool>> GetLabel(string CaseTypeId, string systemAPIUrl)
        {
            //去除所有空格，若为null则默认为空字符串
            CaseTypeId = CaseTypeId?.Replace(" ", string.Empty) ?? string.Empty;

            //获取标签的xpath路径
            string xpath = $"//CaseName[@CaseTypeID='{CaseTypeId}']/ancestor-or-self::*";

            //加载配置xml内容
            string xmlstr = GetConfigFileConnect(systemAPIUrl, "datasynccenter", "case//casename2.0", "config", "xml");
            XDocument xdocument = XDocument.Parse(xmlstr);
            IEnumerable<XElement> nodes = xdocument.XPathSelectElements(xpath);
            //筛选出属性名为“CaseName”并且有值的数据
            var list = nodes.Where(x => !string.IsNullOrWhiteSpace(x.Attribute("CaseName")?.Value)).Select(x => new KeyValuePair<string, bool>(x.Attribute("CaseName").Value, x.Attribute("IsNew")?.Value == "1"));
            if (!list.Any())
            {
                xpath = $"//CaseName[@CaseTypeID='']/ancestor-or-self::*";
                //筛选案件类型为空且属性名为“CaseName”并且有值的数据
                nodes = xdocument.XPathSelectElements(xpath);
                list = nodes.Select(x => new KeyValuePair<string, bool>(x.Attribute("CaseName").Value, x.Attribute("IsNew")?.Value == "1"));
            }
            //颠倒顺序依次是本身=》父级=》父级...
            return list.Reverse().ToList();
        }


        // <summary>
        /// 获取配置文件内容
        /// </summary>
        /// <param name="services">http服务</param>
        /// <param name="systemAPIUrl">systemapi地址</param>
        /// <param name="systemName">系统名称</param>
        /// <param name="moudleName">模块名称</param>
        /// <param name="fileName">文件名称</param>
        /// <param name="fileType">文件类型</param>
        /// <returns></returns>
        public static string GetConfigFileConnect(string systemAPIUrl, string systemName, string moudleName, string fileName, string fileType)
        {
            string re = string.Empty;
            GetConfigFileContentParameterModel parameterModel = new GetConfigFileContentParameterModel();
            parameterModel.SystemName = systemName;
            parameterModel.MoudleName = moudleName;
            parameterModel.FileName = fileName;
            parameterModel.FileType = fileType;
            string dicParmet = JsonConvert.SerializeObject(parameterModel);
            string messge= HttpHelp.HttpPostJson(systemAPIUrl + "/system/config/v1/getfilecontent", dicParmet);
            ApiReturnModel apiReturnInfo = JsonConvert.DeserializeObject<ApiReturnModel>(messge);
            if (apiReturnInfo.result.code == "1")
            {
                JObject job = JObject.Parse(apiReturnInfo.body.ToString());
                re = job.Value<string>("content"); 
            }

            return re;
           
        }

        /// <summary>
        /// 获取配置文件内容接口入口参数模型
        /// </summary>
        public class GetConfigFileContentParameterModel
        {
            /// <summary>
            /// 系统名称
            /// </summary>
            public string SystemName { get; set; }
            /// <summary>
            /// 模块名称
            /// </summary>
            public string MoudleName { get; set; }
            /// <summary>
            /// 文件名称
            /// </summary>
            public string FileName { get; set; }
            /// <summary>
            /// 文件类型
            /// </summary>
            public string FileType { get; set; }
        }

        /// <summary>
        /// api返回结构
        /// </summary>
        public class ApiReturnModel
        {
            public Result result { get; set; }
            public object body { get; set; }
        }

        public class Result
        {
            public string code { get; set; }
            public string message { get; set; }
        }
    }
}
